﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoolERP_Entities;

namespace CoolERP_DAL
{
    public interface IXSDDDAL : IDAL<XSDD>
    {
        List<vXSDD> GetXSDD(Dictionary<string, string> dc, string orderExpr, int? pageIndex, int pageSize, out int totalCount);
        int ConfirmOrder(Guid ID, string HTBH);
    }

    public class XSDDDAL : BaseDAL<XSDD>, IXSDDDAL
    {
        public XSDDDAL(IUnitOfWork context)
            : base(context)
        {
        }

        public List<vXSDD> GetXSDD(Dictionary<string, string> dc, string orderExpr, int? pageIndex, int pageSize, out int totalCount)
        {
            var result = dataContext.vXSDD.AsQueryable();
            if (dc.Count > 0)
            {
                if (dc.ContainsKey("ID") && !string.IsNullOrEmpty(dc["ID"]))
                {
                    Guid keyVal = Guid.Parse(dc["ID"]);
                    result = result.Where(t => t.ID == keyVal);
                }
                if (dc.ContainsKey("DDZT") && !string.IsNullOrEmpty(dc["DDZT"]))
                {
                    int keyVal = Convert.ToInt32(dc["DDZT"]);
                    result = result.Where(t => t.DDZT == keyVal);
                }
                if (dc.ContainsKey("BH") && !string.IsNullOrEmpty(dc["BH"]))
                {
                    string keyVal = dc["BH"];
                    result = result.Where(t => t.BH.Contains(keyVal));
                }
                if (dc.ContainsKey("KHMC") && !string.IsNullOrEmpty(dc["KHMC"]))
                {
                    string keyVal = dc["KHMC"];
                    result = result.Where(t => t.KHJC.Contains(keyVal));
                }
                if (dc.ContainsKey("Department") && !string.IsNullOrEmpty(dc["Department"]))
                {
                    Guid? keyVal = Guid.Parse(dc["Department"]);
                    result = result.Where(t => t.BMID == keyVal);
                }
                if (dc.ContainsKey("Staff") && !string.IsNullOrEmpty(dc["Staff"]))
                {
                    Guid? keyVal = Guid.Parse(dc["Staff"]);
                    result = result.Where(t => t.RYID == keyVal);
                }
                if (dc.ContainsKey("DHSJ1") && !string.IsNullOrEmpty(dc["DHSJ1"]))
                {
                    DateTime keyVal = DateTime.ParseExact(Convert.ToDateTime(dc["DHSJ1"]).ToString("yyyyMMdd"), "yyyyMMdd", System.Threading.Thread.CurrentThread.CurrentCulture);
                    result = result.Where(t => t.DHSJ >= keyVal);
                }
                if (dc.ContainsKey("DHSJ2") && !string.IsNullOrEmpty(dc["DHSJ2"]))
                {
                    DateTime keyVal = DateTime.ParseExact(Convert.ToDateTime(dc["DHSJ2"]).AddDays(1).ToString("yyyyMMdd"), "yyyyMMdd", System.Threading.Thread.CurrentThread.CurrentCulture);
                    result = result.Where(t => t.DHSJ <= keyVal);
                }
                if (dc.ContainsKey("CHSJ1") && !string.IsNullOrEmpty(dc["CHSJ1"]))
                {
                    DateTime keyVal = DateTime.ParseExact(Convert.ToDateTime(dc["CHSJ1"]).ToString("yyyyMMdd"), "yyyyMMdd", System.Threading.Thread.CurrentThread.CurrentCulture);
                    result = result.Where(t => t.CHSJ >= keyVal);
                }
                if (dc.ContainsKey("CHSJ2") && !string.IsNullOrEmpty(dc["CHSJ2"]))
                {
                    DateTime keyVal = DateTime.ParseExact(Convert.ToDateTime(dc["CHSJ2"]).AddDays(1).ToString("yyyyMMdd"), "yyyyMMdd", System.Threading.Thread.CurrentThread.CurrentCulture);
                    result = result.Where(t => t.CHSJ <= keyVal);
                }
            }
            totalCount = result.Count();
            if (!string.IsNullOrEmpty(orderExpr))
                result = SortingExtensions.OrderUsingSortExpression(result, orderExpr);
            if (pageIndex == null)
                return result.ToList();
            else
                return result.Skip(Convert.ToInt32(--pageIndex) * pageSize).Take(pageSize).ToList();
        }

        /// <summary>
        /// 确认订单后转换为合同（-1：产品库中无订单中所需产品，0：确认失败，1：确认成功）
        /// </summary>
        /// <param name="ID">订单ID</param>
        /// <param name="HTBH">合同编号</param>
        /// <returns></returns>
        public int ConfirmOrder(Guid ID, string HTBH)
        {
            int result = 0;
            dataContext.Connection.Open();
            using (var bs = dataContext.Connection.BeginTransaction())
            {
                try
                {
                    XSDD item = dataContext.XSDD.Include("XSDDMXB").FirstOrDefault(t => t.ID == ID);
                    if (item.XSDDMXB.Where(t => t.CPID == null).Count() > 0)
                        result = -1;
                    else
                    {
                        item.DDZT = 1;
                        XSHT ht = new XSHT();
                        ht.ID = Guid.NewGuid();
                        ht.BH = HTBH;
                        ht.HTZT = 0;
                        ht.CHFS = item.CHFS;
                        ht.CHSJ = item.CHSJ;
                        ht.DHSJ = item.DHSJ;
                        ht.KHID = item.KHID;
                        ht.XSBMID = item.BMID;
                        ht.XSRYID = item.RYID;
                        foreach (var mx in item.XSDDMXB)
                        {
                            XSHTMXB entity = new XSHTMXB();
                            entity.ID = Guid.NewGuid();
                            entity.XSHTID = ht.ID;
                            entity.CPID = mx.CPID;
                            entity.DJ = mx.DJ;
                            entity.SL = mx.SL;
                            entity.BZ = mx.BZ;
                            ht.XSHTMXB.Add(entity);
                        }
                        dataContext.XSHT.AddObject(ht);
                        if (Save())
                        {
                            bs.Commit();
                            result = 1;
                        }
                    }
                }
                catch
                {
                    bs.Rollback();
                    return result;
                }
                finally
                {
                    dataContext.Connection.Close();
                }
            }
            return result;
        }
    }
}
